<template>
  <div class="stage">
    <div class="canvas">
      <div class="welcome">
        <img class="logo" src="@/assets/login/login_logo.png" alt="" />
        欢迎登录商家管理平台
      </div>

      <img class="illust" src="@/assets/login/login_ct.png" alt="" />

      <div class="card">
        <div class="card-top-img" />
        <!-- 统一的登录表单（内部自带 tab 切换） -->
        <LoginForm
          ref="loginRef"
          :loading="submitting"
          @submit="handleSubmit"
          @forget="openForgot"
          @onboard="openOnboard"
        />
      </div>
    </div>
  </div>

  <!-- 忘记密码 / 重置密码（复用通用组件） -->
  <PasswordResetDialog v-model="showForgot" :mobile="forgotMobile" :lock-mobile="false" @success="onForgotSuccess" />

  <!-- 选择品牌（仅当返回多品牌时弹出），已抽为组件 -->
  <BrandSelectDialog
    v-model="showDialog"
    :list="brandList"
    v-model:selected-id="selectedBrandId"
    @confirm="chooseAndEnter"
    @cancel="handleCancel"
  />
  <!-- 商家入驻弹窗 -->
  <MerchantOnboardDialog
    v-model="showOnboard"
    :mobile="loginRef?.form?.mobile || ''"
    :lock-mobile="false"
    :need-captcha="true"
    :need-sms="true"
    :show-invite="true"
    success-text="入驻成功，请使用新账号登录"
    @success="onOnboardSuccess"
  />
</template>

<script setup>
  /** ====== imports ====== */
  import LoginForm from "./components/LoginForm.vue";
  import PasswordResetDialog from "./components/PasswordResetDialog.vue";
  import BrandSelectDialog from "./components/BrandSelectDialog.vue";
  import MerchantOnboardDialog from "./components/MerchantOnboardDialog.vue";

  import Local from "tools-utils/storage";
  import { initBackEndControlRoutes } from "@/router/backEndRoute";
  import { NextLoading } from "@/utils/loading";

  /** ====== consts ====== */
  const FORCE_RESET_KEY = "need-force-reset"; // layout 中读取此 key 决定是否强制改密

  /** ====== states ====== */
  const route = useRoute();
  const router = useRouter();
  const userStore = useUserInfoStore();

  const submitting = ref(false);
  const loginRef = ref(null);

  /* ========== 商家入驻 ========== */
  const showOnboard = ref(false); // 控制弹窗
  const onboardMobile = ref("");

  // 打开“商家入驻”
  function openOnboard(mobileFromChild) {
    onboardMobile.value = mobileFromChild || loginRef.value?.form?.mobile || "";
    showOnboard.value = true;
  }
  // 入驻成功
  function onOnboardSuccess({ mobile }) {
    if (mobile && loginRef.value?.form) {
      loginRef.value.form.mobile = mobile; // 回填到登录表单
    }
    loginRef.value?.refreshCaptcha?.(); // 换一张图形码（可选）
    $msg.success("入驻成功，请使用新账号登录");
  }

  /* ========== 忘记密码（仅忘记密码场景；强制改密移到 layout 里） ========== */
  const showForgot = ref(false);
  const forgotMobile = ref("");
  function openForgot(mobileFromForm) {
    // LoginForm 已通过 defineExpose 暴露 form，可兜底取输入的手机
    // forgotMobile.value = mobileFromForm || loginRef.value?.form?.mobile || "";
    forgotMobile.value = "";
    showForgot.value = true;
  }
  function onForgotSuccess({ mobile }) {
    // 回填 & 刷新图形码（可选）
    if (mobile) loginRef.value.form.mobile = mobile;
    loginRef.value?.refreshCaptcha?.();
  }

  /** ====== 品牌候选（抽离了 UI，保留业务）====== */
  const brandList = ref([]); // 接口返回的候选品牌列表
  const showDialog = ref(false); // 是否显示品牌选择弹窗
  const selectedBrandId = ref(""); // 当前选中的 customer.id

  /** ====== 提交登录（第一步）====== */
  async function handleSubmit(payload) {
    try {
      submitting.value = true;
      const candidates =
        payload.mode === "pwd" ? await userStore.LoginByPwd(payload) : await userStore.LoginByCode(payload);

      const list = Array.isArray(candidates) ? candidates : [];
      if (list.length === 0) {
        $msg.error("很抱歉，你的账号暂时不能登录，可能已停用或已过期，如有疑问请联系客服。");
        return;
      }

      // 只有一个品牌：直接选择，不弹窗
      if (list.length === 1) {
        await chooseAndEnter(list[0]);
        return;
      }

      // 多品牌：弹出选择
      brandList.value = list;
      selectedBrandId.value = list[0]?.customer?.id || "";
      showDialog.value = true;
    } catch (e) {
      console.error("[Login] handleSubmit error", e);
      loginRef.value?.refreshCaptcha && loginRef.value.refreshCaptcha();
    } finally {
      submitting.value = false;
    }
  }

  /** ====== 选择品牌（第二步）====== */
  async function chooseAndEnter(item) {
    if (!item?.customer?.id) {
      $msg.error("品牌信息异常");
      return;
    }
    const { id: cid, tenantId } = item.customer;
    try {
      const data = await userStore.ChooseUser({ id: cid, sign: item.sign, tenantId });

      // 记录是否需要强制改密（仅运营/商家需要，BOSS 不用）
      if (String(data?.jumpType) === "1") {
        sessionStorage.setItem(FORCE_RESET_KEY, "1");
      } else {
        sessionStorage.removeItem(FORCE_RESET_KEY);
      }

      $msg.success("登录成功");
      showDialog.value = false;

      // 加载动态路由并跳转
      const isNoPower = await initBackEndControlRoutes();
      loginSuccess(isNoPower);
    } catch (e) {
      console.error("选择品牌失败:", e);
      $msg.error(e?.message || "操作失败");
    }
  }
  function handleCancel() {
    showDialog.value = false;
  }

  /** ====== 登录成功后的跳转 ====== */
  function loginSuccess(isNoPower) {
    if (isNoPower) {
      $msg.warning("抱歉，您没有登录权限");
      Local.clear();
    } else {
      if (route.query?.redirect) {
        router.push({
          path: route.query?.redirect,
          query: Object.keys(route.query?.params || {}).length > 0 ? JSON.parse(route.query?.params) : "",
        });
      } else {
        router.push("/");
      }
      NextLoading.start();
    }
  }
</script>

<style lang="scss" scoped>
  img,
  svg {
    -webkit-user-drag: none;
    user-select: none;
  }

  .stage {
    min-width: 1440px;
    min-height: 900px;
    overflow: auto !important;
    width: 100vw;
    height: 100%;
    display: grid;
    place-items: center;
    background-image: url("@/assets/login/login_bg.jpg");
    background-size: 100% 100%;
    background-position: center;
    background-repeat: no-repeat;
    font-family: "PingFang SC", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
  }
  .canvas {
    position: relative;
    aspect-ratio: 16 / 10;
    width: max(1440px, min(100vw, 160vh));
    height: max(900px, calc((min(100vw, 160vh)) / 16 * 10));
  }
  .welcome {
    position: absolute;
    left: 8.333%;
    top: 6.222%;
    height: 7.111%;
    color: var(--ct1);
    font-weight: 600;
    font-size: 32px;
    display: inline-flex;
    align-items: center;
    gap: 12px;
    user-select: none;

    .logo {
      width: 58px;
      height: auto;
      aspect-ratio: 1;
      object-fit: contain;
    }
  }
  .illust {
    position: absolute;
    left: 2.25%;
    top: 32.6%;
    width: 47.5%;
    height: auto;
  }

  .card {
    position: absolute;
    right: 11.11%;
    top: 30%;
    width: 404px;
    height: 461px;
    border-radius: 20px;
    background: rgba(255, 255, 255, 0.7);
    box-shadow: 0 0 24px 0 #0000000d;
    border: 1px solid #ffffff;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .card-top-img {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 0;
      width: 100%;
      height: 16.78%;
      object-fit: cover;
      background: linear-gradient(180deg, var(--bd8) 2.85%, rgba(255, 242, 240, 0) 100%);
    }
  }
</style>
